package com.tanhua.server.interceptor;


import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器：
 *   1、实现接口 HandlerInterceptor
 *   2、实现内部的方法
 */
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * preHandle ：前置方法，进入controller之前
     * 返回值：
     *   true：验证通过，进入到controller
     *   false：不通过，返回
     * 业务：判断用户请求的token，是否正确
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头 Authorization
        String token = request.getHeader("Authorization");
//        //2、判断token是否可用
//        boolean verifyToken = JwtUtils.verifyToken(token);
//        //3、如果token不可用，响应状态码401
//        if(!verifyToken) {
//            response.setStatus(401); //401
//            return false;
//        }
        //目标：解析token，构造User对象
        //4、调用工具类，解析获取数据
        Claims claims = JwtUtils.getClaims(token);
        //5、构造User对象
        Long id = claims.get("id", Long.class);
        String mobile = claims.get("mobile", String.class);
        User user = new User();
        user.setId(id);
        user.setMobile(mobile);
        //6、存入Threadlocal
        UserHolder.setUser(user);
        return true;
    }

    /**
     * 执行controller之后
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 最终（响应给前端）
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
